//
//  UIButton+block.m
//  runtimeDemo
//
//  Created by kingboyrang on 2021/10/30.
//  Copyright © 2021 wulanzhou. All rights reserved.
//

#import "UIButton+block.h"
#import <objc/runtime.h>

@implementation UIButton (block)

-(void)handleWithBlock:(btnBlock)block{
    if (block) {
//所关联的对象，(获取被关联者的索引key)，需要关联的值,关联策略(assign,strong,retain,copy)
        objc_setAssociatedObject(self, @selector(btnAction:), block, OBJC_ASSOCIATION_COPY_NONATOMIC);
    }
    [self addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)btnAction:(id)sender{
    //获取关联对象的信息，_cmd 就是key
    btnBlock block= objc_getAssociatedObject(self, _cmd);
    if (block) {
        block(sender);
    }
}

//关联属性
- (void)setButtonTypeName:(NSString *)name{
    objc_setAssociatedObject(self, &proKey, name, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (NSString *)buttonTypeName{
    return objc_getAssociatedObject(self,&proKey);
}

@end
